package com.hunttown.mes.manage.controller._erp;

import com.hunttown.mes.common.utils.FastJsonUtils;
import com.hunttown.mes.common.utils.IpUtils;
import com.hunttown.mes.common.utils.SystemUtils;
import com.hunttown.mes.manage.controller.common.AdminBaseClass;
import com.hunttown.mes.manage.controller.common.ModelService;
import com.hunttown.mes.manage.service.TransportManageDepRelManageService;
import com.hunttown.mes.manage.service.TransportOperateLogManageService;
import com.hunttown.mes.rpc.domain.TransportManageDepRelDTO;
import com.hunttown.mes.rpc.domain.query.AnalysisManageDTOQuery;
import com.hunttown.mes.rpc.domain.query.TransportManageDepRelDTOQuery;
import com.hunttown.common.domain.Page;
import com.hunttown.mes.common.OperateCode;
import com.hunttown.mes.common.utils.JSONUtils;
import com.hunttown.mes.manage.service.TransportDepartmentManageService;
import com.hunttown.mes.manage.service.AnalysisManageManageService;
import com.hunttown.mes.rpc.domain.AnalysisManageDTO;
import com.hunttown.mes.rpc.domain.TransportDepartmentDTO;
import com.hunttown.mes.rpc.domain.query.TransportDepartmentDTOQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

import static com.hunttown.mes.common.utils.PageUtils.PagePackage;

/**
 * @title: 部门管理
 * @author: wangjunfu
 * @date: 2019-04-28 16:28:58
 * @description:
 */
@Controller
@RequestMapping(value = "/erp/department")
public class DepartmentController {

    private final static Logger logger = LoggerFactory.getLogger(DepartmentController.class);

    private final AnalysisManageManageService manageService;
    private final TransportDepartmentManageService departmentService;
    private final ModelService modelService;
    private final TransportOperateLogManageService logService;
    private final TransportManageDepRelManageService depRelManageService;

    @Autowired
    public DepartmentController(TransportDepartmentManageService departmentService, AnalysisManageManageService manageService, ModelService modelService, TransportOperateLogManageService logService, TransportManageDepRelManageService depRelManageService) {
        this.departmentService = departmentService;
        this.manageService = manageService;
        this.modelService = modelService;
        this.logService = logService;
        this.depRelManageService = depRelManageService;
    }

    // 首页
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(HttpServletRequest request, Model model, TransportDepartmentDTOQuery objDTOQuery) {

        Page<TransportDepartmentDTO> dataPage = departmentService.getForPage(objDTOQuery);

        // 实时更新列表信息
        for (TransportDepartmentDTO item : dataPage.getItems()) {
            //取出部门成员
            TransportManageDepRelDTOQuery query = new TransportManageDepRelDTOQuery();
            query.setTableId(13);
            query.setDepId(item.getId());
            query.setPageSize(1000);
            Page<TransportManageDepRelDTO> deppage = depRelManageService.getForPage(query);

            //取出成员姓名
            List<String> names = new ArrayList<>();
            for (TransportManageDepRelDTO cli : deppage.getItems()) {
                names.add(modelService.getManageName(cli.getRecordId()) + (cli.getDutyId() == 1 ? "（主管）" : ""));
            }
            item.setMembers(String.join("，", names));
        }

        model.addAttribute("page", dataPage);
        model.addAttribute("PagePackage", PagePackage(dataPage.getPn(), dataPage.getStart(), dataPage.getPageSize(), dataPage.getTotalPages(), dataPage.getTotalItems()));

        List<TransportDepartmentDTO> departList = departmentService.getListByRecursion(dataPage.getItems(), 0, "|");
        model.addAttribute("departList", departList);
        model.addAttribute("dtoQuery", objDTOQuery);

        //判断是否管理员
        String pin = AdminBaseClass.getPin(request);
        AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
        model.addAttribute("isSuper", curr_obj.getIsSuper());

        return "erp/department/index";
    }

    // 编辑
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Model model, Integer id) {
        id = id == null ? 0 : id;

        TransportDepartmentDTO obj = new TransportDepartmentDTO();
        obj.setId(id);
        obj.setAuthorizeNumber(8);
        if (id > 0) {
            obj = departmentService.getById(id);
        }
        model.addAttribute("Obj", obj);

        // 获取列表
        TransportDepartmentDTOQuery query = new TransportDepartmentDTOQuery();
        query.setStopFlag(0);
        query.setPageSize(1000);
        Page<TransportDepartmentDTO> list = departmentService.getForPage(query);
        if (list != null) {
            model.addAttribute("childList", departmentService.getListByRecursion(list.getItems(), 0, "|"));
        }

        return "erp/department/edit";
    }

    // 保存 Ajax异步调用
    @RequestMapping(value = "/saveEdit", method = RequestMethod.POST)
    @ResponseBody
    public String saveEditNotify(HttpServletRequest request, TransportDepartmentDTO objDTO) {

        //结果返回，结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();
        try {
            if (objDTO.getIsAuthor() == null) {
                objDTO.setIsAuthor(0);
            }
            if (objDTO.getStopFlag() == null) {
                objDTO.setStopFlag(0);
            }

            //新增时检验是否唯一
            if (objDTO.getId() == null || objDTO.getId() <= 0) {
                TransportDepartmentDTOQuery query = new TransportDepartmentDTOQuery();
                query.setDepName(objDTO.getDepName());
                TransportDepartmentDTO obj = departmentService.getByQuery(query);

                if (obj != null && obj.getId() > 0) {
                    //说明已经有此记录了，不能插入。
                    map = OperateCode.CompositionResult(map, -10, "此记录英文名称已存在，请重新输入！");
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }

            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);

            if (objDTO.getId() == null || objDTO.getId() <= 0) {
                //新增
                //设置初始值
                objDTO.setChargeId(0);
                objDTO.setAdminId(curr_obj.getId());
                objDTO.setCreateTime(new Date());
                objDTO.setDeleteFlag(0);

                objDTO = departmentService.insert(objDTO);

                if (objDTO == null || objDTO.getId() <= 0) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            } else {
                //更新
                //将不需要更新的字段设置为NULL
                objDTO.setDepName(null);

                Boolean isNext = departmentService.updateInfoById(objDTO);
                if (!isNext) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }

            //region *** 更新信息完毕记录操作日志 ***
            logService.insertSimple(1, 61, objDTO.getId(), 2,
                    "更新部门信息",
                    FastJsonUtils.toJSONString(objDTO),
                    curr_obj.getId(),
                    IpUtils.getClientIp(request),
                    SystemUtils.getBrowserInfo(request));
            //endregion

            //操作成功 结果返回
            map = OperateCode.CompositionResult(map, 1);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }

    /**
     * 通过id删除 ajax异步
     *
     * @param id 记录id
     * @return json
     */
    @RequestMapping(value = "/deleteById", method = RequestMethod.POST)
    @ResponseBody
    public String deleteNotify(HttpServletRequest request, Integer id) {

        // 结果返回结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        if (id == null || id <= 0) {
            map = OperateCode.CompositionResult(map, -10, "请选择要删除的记录！");
            result = JSONUtils.toJSON(map);
            return result;
        }

        try {
            Boolean isNext = departmentService.delete(id);

            //region *** 更新信息完毕记录操作日志 ***
            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
            logService.insertSimple(1, 61, id, 4,
                    "删除部门信息",
                    "部门删除：" + (isNext ? "成功" : "失败") + "：" + id,
                    curr_obj.getId(),
                    IpUtils.getClientIp(request),
                    SystemUtils.getBrowserInfo(request));
            //endregion

            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }

    // 状态改变 Ajax异步
    @RequestMapping(value = "/changeFlag", method = RequestMethod.POST)
    @ResponseBody
    public String openOrStopFlag(HttpServletRequest request, Integer id, Integer status) {
        //结果返回，结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            Boolean isNext = departmentService.changeState(id, status);

            //region *** 更新信息完毕记录操作日志 ***
            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
            logService.insertSimple(1, 61, id, 4,
                    "启停用部门信息",
                    "部门启停用：" + (isNext ? "成功" : "失败") + "：" + id,
                    curr_obj.getId(),
                    IpUtils.getClientIp(request),
                    SystemUtils.getBrowserInfo(request));
            //endregion

            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }

    // 组内成员（弃用，有新版）
    @RequestMapping(value = "/member", method = RequestMethod.GET)
    public String member(Model model, Integer depId, Integer pn) {
        depId = (depId == null ? 0 : depId);
        pn = (pn == null ? 1 : pn);

        //根据 depId 取当前及下级 id 集合

        if (depId > 0) {
            List<Integer> depid_list = departmentService.getChildIdsByRecursion(depId);

            AnalysisManageDTOQuery query = new AnalysisManageDTOQuery();
            query.setDepIds(depid_list);
            query.setPageSize(20);
            query.setPn(pn);

            Page<AnalysisManageDTO> dataPage = manageService.getForPage(query);

            // 获取权限信息
            dataPage = manageService.getPageRoleName(dataPage);

            // 实时更新列表信息
            if (dataPage != null && dataPage.getItems().size() > 0) {
                for (AnalysisManageDTO item : dataPage.getItems()) {
                    item.setDepName(departmentService.getRootNameByRecursion(item.getDepId(), ""));
                }
            }

            model.addAttribute("page", dataPage);
            model.addAttribute("PagePackage", PagePackage(dataPage.getPn(), dataPage.getStart(), dataPage.getPageSize(), dataPage.getTotalPages(), dataPage.getTotalItems()));

        }

        model.addAttribute("depId", depId);

        return "erp/department/member";
    }

    //region 获取部门列表
    @RequestMapping(value = "/selectDepartment", method = RequestMethod.POST)
    public String selectDepartment(Model model) {

        //部门列表
        modelService.getDepList(model);

        return "basic/manage/dep-select-model";
    }
    //endregion

    //region 根据人员取出所属部门，如有多个取最早的一个
    @RequestMapping(value = "/getInfoByAdminid", method = RequestMethod.POST)
    @ResponseBody
    public Map<Object, Object> getInfoByAdminid(Integer adminId) {

        Map<Object, Object> map = new HashMap<>();
        map.put("returnCode", 0);
        map.put("depId", 0);
        map.put("depName", "");

        if (adminId == null || adminId <= 0) {
            return map;
        }

        int depId = depRelManageService.getDepIdByAdminId(adminId);
        if (depId == 0) {
            return map;
        }

        map.put("depId", depId);
        map.put("depName", departmentService.getDepName(depId));

        map.put("returnCode", 1);
        return map;
    }
    //endregion
}